package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 任务一：查询特定用户及其拥有的所有角色
    @GetMapping("/username/{username}")
    public Map<String, Object> getUserWithRolesByUsername(@PathVariable String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.findUserWithRolesByUsername(username);
            result.put("success", true);
            result.put("data", user);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 任务三：根据条件搜索用户，并连带其角色和权限信息
    @GetMapping("/search")
    public Map<String, Object> searchUsersWithRolesAndMenus(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        try {
            List<User> users = userService.findUsersWithRolesAndMenusByCondition(
                    username, email, status, page, pageSize);
            Long total = userService.countUsersByCondition(username, email, status);

            result.put("success", true);
            result.put("data", users);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 任务四：更新用户角色
    @PostMapping("/{userId}/roles")
    public Map<String, Object> updateUserRoles(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        Map<String, Object> result = new HashMap<>();
        try {
            userService.updateUserRoles(userId, roleIds);
            result.put("success", true);
            result.put("message", "用户角色更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }
}
